package com.jacksen.demo.view.surface

import android.opengl.GLES20
import android.opengl.GLSurfaceView
import android.opengl.Matrix
import android.util.Log
import javax.microedition.khronos.egl.EGLConfig
import javax.microedition.khronos.opengles.GL10

class CameraDisplay(val glSurfaceView: GLSurfaceView) : GLSurfaceView.Renderer {

    lateinit var triangle: Triangle

    private val mMVPMatrix = FloatArray(16)
    private val mProjectionMatrix = FloatArray(16)
    private val mViewMatrix = FloatArray(16)

    companion object {
        const val TAG = "CameraDisplay"
    }

    init {
        glSurfaceView.setEGLContextClientVersion(2)
        glSurfaceView.setRenderer(this)
        glSurfaceView.renderMode = GLSurfaceView.RENDERMODE_WHEN_DIRTY
        Log.d(TAG, "init -- ")
    }


    override fun onSurfaceCreated(gl: GL10, config: EGLConfig) {
        Log.d(TAG, "onSurfaceCreated -- " + Thread.currentThread().toString())
        // 设置背景的颜色
        GLES20.glClearColor(0.0f, 0.0f, 0.0f, 1.0f)
        triangle = Triangle()
    }

    override fun onSurfaceChanged(gl: GL10, width: Int, height: Int) {
        Log.d(TAG, "onSurfaceChanged -- " + Thread.currentThread().toString())
        GLES20.glViewport(0, 0, width, height);
        val ratio = width.toFloat() / height
        // // 此投影矩阵在onDrawFrame()中将应用到对象的坐标
        Matrix.frustumM(mProjectionMatrix, 0, -ratio, ratio, -1f, 1f, 3f, 7f)
    }

    override fun onDrawFrame(gl: GL10) {
        Log.d(TAG, "onDrawFrame -- " + Thread.currentThread().toString())
        // 重绘背景颜色
        GLES20.glClear(GLES20.GL_COLOR_BUFFER_BIT)

        // 设置相机的位置 (视图矩阵)
        Matrix.setLookAtM(mViewMatrix, 0, 0f, 0f, -3f, 0f, 0f, 0f, 0f, 1.0f, 0.0f);
        // 计算投影和视图变换
        Matrix.multiplyMM(mMVPMatrix, 0, mProjectionMatrix, 0, mViewMatrix, 0)

        triangle.draw(mMVPMatrix)
    }

    fun onResume() {
        Log.d(TAG, "glSurfaceView.onResume() before -- " + Thread.currentThread().toString())
        glSurfaceView.onResume()
        Log.d(TAG, "glSurfaceView.onResume() after -- " + Thread.currentThread().toString())
    }

    fun onPause() {
        Log.d(TAG, "glSurfaceView.onPause() before -- " + Thread.currentThread().toString())
        glSurfaceView.onPause()
        Log.d(TAG, "glSurfaceView.onPause() after -- " + Thread.currentThread().toString())
    }

    fun render() {
        Log.d(TAG, "render -- " + Thread.currentThread().toString())
        glSurfaceView.requestRender()
    }
}